<template>
  <div>
    <h1>USB Serial Port Listener</h1>
    <button @click="requestPort">Request Port</button>
    <div v-if="port">
      <p>Port connected: {{ port.getInfo().usbVendorId }} - {{ port.getInfo().usbProductId }}</p>
    </div>
    <div v-else>
      <p>No port connected</p>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, onBeforeUnmount } from 'vue';

export default defineComponent({
  name: 'UsbSerialPortListener',
  setup() {
    const port = ref<SerialPort | null>(null);

    const requestPort = async () => {
      try {
        const selectedPort = await navigator.serial.requestPort();
        await selectedPort.open({ baudRate: 9600 });
        port.value = selectedPort;
      } catch (error) {
        console.error('Error opening port:', error);
      }
    };

    const handleConnect = (event: Event) => {
      console.log('USB device connected:', event);
      // Optionally, you can request the port here
    };

    const handleDisconnect = (event: Event) => {
      console.log('USB device disconnected:', event);
      port.value = null;
    };

    onMounted(() => {
      navigator.serial.addEventListener('connect', handleConnect);
      navigator.serial.addEventListener('disconnect', handleDisconnect);
    });

    onBeforeUnmount(() => {
      navigator.serial.removeEventListener('connect', handleConnect);
      navigator.serial.removeEventListener('disconnect', handleDisconnect);
    });

    return {
      port,
      requestPort,
    };
  },
});
</script>

<style scoped>
h1 {
  font-size: 24px;
  margin-bottom: 16px;
}
button {
  margin-bottom: 16px;
}
</style>
